<?php
namespace app\admin\service;
use think\Db;
use think\Loader;
class  Consul{


    //咨询类型
    function consulType(){
        $paginate = 15;
        $info  = Db::name('consult_type')->order('ct_sort desc,ct_addtime desc')->paginate($paginate);
        $page  = $info->render();
        $data['list'] = $info;
        $data['page'] = $page;
        return $data;
    }

    //查询咨询类型
    function consulTypeFind($consult_type_id){
        $data = Db::name('consult_type')->where('consult_type_id',$consult_type_id)->find();
        if(empty($data)){
            return messageInfo('101','数据查询失败');
        }
        return messageInfo('202','数据查询成功',$data);
    }

    //咨询类型新增与编辑
    function consulTyupeRequestApi($ct_name,$ct_sort,$consult_type_id){
        if(empty($ct_name)){
            return messageInfo('101','分类名必需填写');
        }
        if(!is_numeric($ct_sort)){
            return messageInfo('101','排序必需填写数字');
        }
        $data_array['ct_name'] = $ct_name;
        $data_array['ct_sort'] = $ct_sort;
        $consult_type = Db::name('consult_type');
        if(empty($consult_type_id)){
            $data_array['ct_addtime']   = date('Y-m-d H:i:s');
            $a = $consult_type->insert($data_array);
            $return_name = '新增';
        }else{
            $data_array['consult_type_id'] = $consult_type_id;
            $a = $consult_type->update($data_array);
            $return_name = '编辑';
        }
        if($a){
            $response = messageInfo('202',$return_name.'成功');
        }else{
            $response = messageInfo('101',$return_name.'失败');
        }
        return $response;
    }

    //咨询类型删除
    function consulTypeDeleteApi($consult_type_id){
        if(empty($consult_type_id)){
            return messageInfo('101','系统参数错误');
        }
        $a = Db::name('consult_type')->where('consult_type_id',$consult_type_id)->delete();
        if(!$a){
            return messageInfo('101','删除失败');
        }
        return messageInfo('202','删除成功');
    }

    //咨询列表
    function consultList(){
        $where    = '';
        $uid      = input('uid');
        if(!empty($uid)){
          $where['b.u_phone'] = $uid;
        }
        $consult_type_id = input('consult_type_id');
        if(!empty($consult_type_id)){
            $where['a.consult_type_id'] = $consult_type_id;
        }
        $ct_state = input('ct_state');
        if(!empty($ct_state)){
            $where['a.ct_state'] = $ct_state;
        }else{
            $where['a.ct_state'] = 1;
        }
        $stime  = input('stime');
        $otime  = input('otime');
        if(!empty($stime) || !empty($otime)){
            if(!empty($stime) && !empty($otime)){
                $where['a.ct_addtime']=array(array('egt',"{$stime}%"),array('elt',"{$otime}%")) ;
            }else if(!empty($stime)){
                $where['a.ct_addtime'] = array('gt',$stime);
            }else{
                $where['a.ct_addtime'] = array('gt',$otime);
            }
        }
        $field    = "a.*,b.ct_name,c.u_phone,c.u_nickname";
        $paginate = 15;
        $pages    = input('page');
        $join     = [
            ['lt_consult_type b','a.consult_type_id=b.consult_type_id','LEFT'],
            ['lt_user c','a.u_uid=c.u_uid','LEFT'],
        ];
        $param         = input ( 'param.' );
        $list = Db::name('consult')->alias('a')->join($join)->where($where)->field($field)->order('a.ct_addtime desc')->paginate($paginate,false,['page'=>$pages?$pages:'']);
        $page = $list->render();
        $data['list']  = $list;
        $data['page']  = $page;// 分页显示输出*/
        $data['post']  = $param?$param:null;
        return $data;
    }

    //咨询类型查询
    function consultTypeSelect(){
        $list = Db::name('consult_type')->select();
        return $list;
    }

    //短信推送设置数据
    function consultSie(){
        $paginate = 15;
        $join     = [
            ['lt_admin b','a.admin_id=b.admin_id','LEFT'],
        ];
        $info  = Db::name('consult_push_sie')->alias('a')->join($join)->field('a.*,b.a_fullname,b.a_phone')->order('a.cps_addtime desc')->paginate($paginate);
        $page  = $info->render();
        $data['list'] = $info;
        $data['page'] = $page;
        return $data;
    }

    //短信推送设置
    function consulPushRequestApi($a_username){
        if(empty($a_username)){
            return messageInfo('101','管理员必需填写');
        }
        $admin_id = Db::name('admin')->where('a_username',$a_username)->value('admin_id');
        if(count($admin_id) <= 0){
            return messageInfo('101','账号不存在');
        }
        $consult_push_sie = Db::name('consult_push_sie');
        $decide_errot     = $consult_push_sie->where('admin_id',$admin_id)->count();
        if($decide_errot >= 1){
            return messageInfo('101','此账号已设置过了！');
        }
        $data_array['admin_id']    = $admin_id;
        $data_array['cps_addtime'] = date('Y-m-d H:i:s');
        $a = $consult_push_sie->insert($data_array);
        if(!$a){
            return messageInfo('101','设置失败！');
        }
        return messageInfo('202','设置成功！');
    }

    //短信推送设置，删除
    function consulPushDeleteApi($consult_push_sie_id){
        if(empty($consult_push_sie_id)){
            return messageInfo('101','系统参数错误');
        }
        $a = Db::name('consult_push_sie')->where('consult_push_sie_id',$consult_push_sie_id)->delete();
        if(!$a){
            return messageInfo('101','删除失败');
        }
        return messageInfo('202','删除成功');
    }

    //待回复咨询
    function meConsult(){

        $stime  = input('stime');
        $otime  = input('otime');
        if(!empty($stime) || !empty($otime)){
            if(!empty($stime) && !empty($otime)){
                $where['a.ct_addtime']=array(array('egt',"{$stime}%"),array('elt',"{$otime}%")) ;
            }else if(!empty($stime)){
                $where['a.ct_addtime'] = array('gt',$stime);
            }else{
                $where['a.ct_addtime'] = array('gt',$otime);
            }
        }
        $Admin_user_lvtuan   = session('Admin_user_lvtuan');
        $where['a.admin_id'] = $Admin_user_lvtuan['admin_id'];
        $where['a.cp_state'] = 1;
        $field    = "a.admin_id,a.consult_push_id,a.consult_id,a.cp_state,a.cp_addtims,b.ct_name,c.u_phone,c.u_nickname,d.ct_details,d.ct_title,f.cr_details as fcr_details";
        $paginate = 15;
        $pages    = input('page');
        $join     = [
            ['lt_consult d','a.consult_id=d.consult_id','LEFT'],
            ['lt_consult_type b','d.consult_type_id=b.consult_type_id','LEFT'],
            ['lt_user c','a.u_uid=c.u_uid','LEFT'],
            ['lt_consult_reply f','a.consult_reply_id=f.consult_reply_id','LEFT'],
        ];
        $param         = input ( 'param.' );
        $list = Db::name('consult_push')->alias('a')->join($join)->where($where)->field($field)->order('a.cp_addtims desc')->paginate($paginate,false,['page'=>$pages?$pages:'']);
        $page = $list->render();
        $data['list']  = $list;
        $data['page']  = $page;// 分页显示输出*/
        $data['post']  = $param?$param:null;
        return $data;
    }

    //待回复咨询详情
    function meReplsyFind($consult_id){
        $ct_details = Db::name('consult')->where('consult_id',$consult_id)->value('ct_details');
        if(empty($ct_details)){
            return messageInfo('101','查询失败');
        }
        return messageInfo('202','查询成功',$ct_details);
    }

    //咨询详情
    function consultDatals($consult_id){
        $join     = [
            ['lt_consult_type b','a.consult_type_id=b.consult_type_id','LEFT'],
            ['lt_user c','a.u_uid=c.u_uid','LEFT'],
        ];
        $data['data']              = Db::name('consult')->alias('a')->join($join)->where('a.consult_id',$consult_id)->field('a.*,b.ct_name,c.u_phone,c.u_nickname,c.u_img')->find();
        $join_a  = [
            ['lt_consult_push b','a.consult_reply_id=b.consult_reply_id','LEFT'],
        ];
        $data['list'] = Db::name('consult_reply')->alias('a')->join($join_a)->where('a.consult_id',$consult_id)->field('a.*,b.cp_state,b.u_uid as uid')->order('a.cr_addtims asc')->select();
        if(!empty($data['list'])){
            foreach( $data['list'] as $k=>$v){
                if($v['cr_type'] == 1){
                    $user_data = Db::name('user')->where('u_uid',$v['uid'])->field('u_nickname,u_img,u_phone')->find();
                    $data['list'][$k]['user_name'] = $user_data['u_nickname']?$user_data['u_nickname']:$user_data['u_phone'];
                    $data['list'][$k]['img']       = $user_data['u_img'];
                }else{
                    $user_data = Db::name('admin')->where('admin_id',$v['u_uid'])->field('a_fullname,a_img')->find();
                    $data['list'][$k]['user_name'] = $user_data['a_fullname'];
                    $data['list'][$k]['img']       = $user_data['a_img'];
                }
            }
        }
        return $data;
    }

    //咨询回复
    function meConsulRequestApi($fcr_details,$consult_id){
     try{
        if(empty($consult_id)){
            return messageInfo('101','系统参数错误');
        }
        if(empty($fcr_details)){
            return messageInfo('101','回复必需填写');
        }
        $consult_reply     = Db::name('consult_reply');
        $Admin_user_lvtuan = session('Admin_user_lvtuan');
        $consult_push      = Db::name('consult_push');

        //查询属于那个后台用户
        $where['consult_id'] = $consult_id;
        $where['admin_id']   = $Admin_user_lvtuan['admin_id'];
        $push_count          = $consult_push->where($where)->count();
         if($push_count <= 0){
             return messageInfo('101','你没有此咨询的回复权限！');
         }
        //开启事务
        $consult_reply->startTrans();
        //更改推送后台信息表

        $where['cp_state']   = 1;
        $a = $consult_push->where($where)->setField('cp_state',2);
        if($a === false){
            $consult_reply->rollback();
            return messageInfo('101','回复失败1');
        }
        $date = date('Y-m-d H:i:s');
        //查询用户信息
        $join = [['lt_user b','a.u_uid=b.u_uid','LEFT']];
        $user_phone = Db::name('consult')->alias('a')->join($join)->where('a.consult_id',$consult_id)->value('u_phone');
        if(!$user_phone){
            $consult_reply->rollback();
            return messageInfo('101','回复失败2');
        }
         //写入回复总数
         $p = Db::name('consult')->where('consult_id',$consult_id)->setInc('ct_count',1);
         if(!$p){
             $consult_reply->rollback();
             return messageInfo('101','回复失败!');
         }
        //写入记录表
        $data_array_log = array(
            'pl_phone'   => $user_phone,
            'pl_details' => $fcr_details,
            'pl_type'    => 2,
            'pl_addtime' => $date
        );
        $b = Db::name('push_log')->insert($data_array_log);
        if(!$b){
            $consult_reply->rollback();
            return messageInfo('101','回复失败3');
        }
         $admin    =  session('Admin_user_lvtuan');
         $a_fullname = $admin['a_fullname'];

        //写入回复表
        $data_array = array(
            'consult_id' => $consult_id,
            'u_uid'      => $Admin_user_lvtuan['admin_id'],
            'cr_type'    => 2,
            'cr_state'   => 1,
            'cr_details' => $fcr_details,
            'cr_addtims' => $date,
        );
        $c = $consult_reply->insert($data_array);
        if(!$c){
            $consult_reply->rollback();
            return messageInfo('101','回复失败4!');
        }
        $consult_reply->commit();
         //发送短信
        $this->dataPush($user_phone,$a_fullname,$fcr_details,2);
        $response = messageInfo('202','回复成功!');
    } catch (Exception  $e) {
        $response = messageInfo('101','服务器错误');
    }
        return $response;
    }


    //短信推送
    function dataPush($phone,$a_fullname,$details,$type=1){
        if ($type == 2) {
            $arrt['up_phone'] = $phone;
            $arrt['product']  = '咨询回复';
            $arrt['succeed']  = '回复成功';
            $arrt['errot']    = '回复失败6';
        }
        // 短信内容参数
    /*    Loader::import('Alidayu.AlidayuClient', EXTEND_PATH, '.class.php');
        Loader::import('Alidayu.Request.SmsNumSend', EXTEND_PATH, '.class.php');
        $client  = new \Alidayu\AlidayuClient();
        $request = new \Alidayu\Request\SmsNumSend ();
        $smsParams = array ('name' => $arrt['up_phone'],'details' => $details);
        // 设置请求参数
        $req  = $request->setSmsTemplateCode (config('AlidayuPush'))->setRecNum ( $arrt['up_phone'] )->setSmsParam ( json_encode ( $smsParams ) )->setSmsFreeSignName (config('AlidayuName'))->setSmsType ( 'normal' )->setExtend ( 'demo' );
        $data = $client->execute ( $req );

        if(!array_key_exists('alibaba_aliqin_fc_sms_num_send_response',$data) ){
            return messageInfo ( '101', $arrt['errot'] );
        }*/
        Loader::import('Aldy.Sms', EXTEND_PATH, '.class.php');
        $cofig ['templateCode'] = config('AlidayuID_HF');
        $sms = new \Sms($cofig);
        $smsParams = array ('name' => $arrt['up_phone'],'user'=>$a_fullname,'details'=>$details);
        $data = $sms->send_verify($arrt['up_phone'], json_encode ( $smsParams ));
        if ($data['Code'] == 'OK' && $data['Message'] == 'OK') {
            $response = messageInfo ( '202', $arrt['succeed'] );
        } else {
            $response = messageInfo ( '101', $arrt['errot'] );
        }
        return $response;
    }


    //咨询操作
    function consulHandleApi($consult_id,$state){
        if(empty($consult_id) || empty($state)){
            return messageInfo('101','系统参数错误');
        }
        $a = Db::name('consult')->where('consult_id',$consult_id)->setField('ct_state',$state);
        if(!$a){
            return messageInfo('101','操作失败!');
        }
        $response = messageInfo('202','操作成功!');
        return $response;
    }

}
